<?php

namespace App\Service;

use Exception;
use GuzzleHttp\Exception\GuzzleException;
use Hyperf\Guzzle\ClientFactory;
use Hyperf\Di\Annotation\Inject;

class SlWechatService {

    /**
     * @Inject
     * @var ClientFactory
     */
    protected ClientFactory $clientFactory;

    private array $config = [
        'appid'     => 'wxc3a18da295187a07',
        'gameid'    => '1294',
        'channelid' => '100000714',
        'appkey'    => '70E2153BF0E2DCAEC629E877C2B021F5',
        'appsecret' => 'B8C75D3B99085D57B6FE4D01A26765B4',
        'publickey' => 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDLMDb7/eNgf7fDKzekQtcqiePYHLxUsfnyVlKRhyQ2GRHsX/Umpscjef8RcXS2B8gErt0bEelCAXMlhEEIeBtyNxkt0wbp19L54Dq628nfBjkiH+9TVt9bkiqOj24ngWJ3ATc760i5+c/7auRCJcoWxJCLexcLPwY/PlUyUB7KtwIDAQAB'
    ];

    //肆狼版号包 只有渠道ID不同
    private array $config_bh = [
        'appid'     => 'wxc3a18da295187a07',
        'gameid'    => '1294',
        'channelid' => '100000778',
        'appkey'    => '70E2153BF0E2DCAEC629E877C2B021F5',
        'appsecret' => 'B8C75D3B99085D57B6FE4D01A26765B4',
        'publickey' => 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDLMDb7/eNgf7fDKzekQtcqiePYHLxUsfnyVlKRhyQ2GRHsX/Umpscjef8RcXS2B8gErt0bEelCAXMlhEEIeBtyNxkt0wbp19L54Dq628nfBjkiH+9TVt9bkiqOj24ngWJ3ATc760i5+c/7auRCJcoWxJCLexcLPwY/PlUyUB7KtwIDAQAB'
    ];

    /**
     * 登录检校
     * @param array $gameInfo
     * @param string $code
     * @param int $type 1:普通版 2:版号包
     * @return array
     * @throws GuzzleException
     * @throws Exception
     */
    public function loginVerify(array $gameInfo, string $code, int $type = 1): array {
        $client = $this->clientFactory->create(['verify' => false]);
        $url = 'https://sdk.17a.cn/login/verify';
        $postData = [
            'access_token' => $code,
            'channelid'    => $this->config['channelid'],
            'time'         => time(),
        ];
        if ($type == 2) {
            $postData['channelid'] = $this->config_bh['channelid'];
        }
        $postData['sign'] = $this->signData($postData);

        try {
            $response = $client->post($url, [
                'json' => $postData
            ]);
            $res = json_decode($response->getBody()->getContents(), true);
            if ($response->getStatusCode() != 200 || $res['code'] != 0) {
                var_dump('肆狼登录检测失败,非200---start');
                var_dump($postData);
                var_dump($res);
                var_dump('肆狼登录检测失败,---end');
                throw new Exception('登陆失败，请联系管理员');
            }
            $return = $res['data'];
        } catch (Exception $e) {
            var_dump('肆狼登录检测失败');
            var_dump($e->getMessage());
            throw new Exception('登陆失败，请联系管理员');
        }
        return $return;
    }

    private function signData(array $data): string {
        ksort($data);
        $str = implode('', $data) . $this->config['appsecret'];
        return md5($str);
    }

    public function payBackVerify(string $data, string $sign): bool {
        $pubKey = $this->config['publickey'];
        //这是测试key
        //$pubKey = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC7sYBBuBGxToMUKWHdnu03jDhFW/24PWLlXzYxdXPFPQTIR4O6jm96FXJ4P72YVcPTDIHmR9HmXfUM7HVv9oz8Ep3ZsyzjltM9Lvg3iyMTE/gu+Tlk+iFrMeGmURRobVvxEzurY3wfhOjaKrW4QrGlBmgkblFTOfz13dlKzloHMwIDAQAB';
        $pubKey = '-----BEGIN PUBLIC KEY-----' . PHP_EOL
            . chunk_split($pubKey, 64, PHP_EOL)
            . '-----END PUBLIC KEY-----' . PHP_EOL;

        $res = openssl_get_publickey($pubKey);
        return (bool)openssl_verify($data, base64_decode($sign), $res, OPENSSL_ALGO_SHA1);
    }

    /**
     * 请求肆狼敏感词检测接口
     * @param array $data
     * @return string|int  1.可以发言 0.无法发言
     * @throws GuzzleException
     */
    public function checkWord(array $data): string|int {
        $timeout = 2;
        $client = $this->clientFactory->create(['verify' => false, 'timeout' => $timeout]);//超时时间根据使用方式会有所不同
        $url = "https://sdk.17a.cn/apiv3/msg/match_service";

        $postData = [
            'channelid' => $this->config['channelid'],
            'userid'    => $data['openid'],
            'to_check'  => $data['msg'],
            'by_pinyin' => 1,
        ];
        $signStr = md5($this->config['channelid'] . $data['openid'] . date('Ymd'));
        $json = array_merge($postData, [
            'sign' => $signStr,
        ]);
        try {
            $response = $client->post($url, [
                'json' => $json
            ]);
        } catch (Exception $e) {
            var_dump($e->getMessage());
            var_dump('聊天检测本次超时啦');
            return 1;
        }
        if ($response->getStatusCode() != 200) {
            var_dump('聊天检测本次失败啦');
            return 1;//超时
        } else {
            $res = json_decode($response->getBody()->getContents(), true);
            var_dump($res);
            if ($res['code'] != 0) {
                return 0;
            } else {
                return 1;
            }
        }
    }
}